import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:interview/components/app/app_prompt_overlay.dart';
import 'package:interview/components/page/page_nav_bar.dart';
import 'package:interview/components/status_bar_warpper.dart';
import 'package:interview/pages/record/components/record_info.dart';
import 'package:interview/pages/record/components/record_list.dart';
import 'package:interview/pages/record/components/record_play.dart';
import 'package:interview/pages/record/components/record_player.dart';
import 'package:interview/pages/record/database_helper.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:interview/utils/logger.dart';
import 'package:interview/utils/permission_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class RecordPage extends StatefulWidget {
  const RecordPage({super.key});

  @override
  State<RecordPage> createState() => _RecordPageState();
}


class _RecordPageState extends State<RecordPage> {
  final FlutterSoundPlayer _audioPlayer = FlutterSoundPlayer(); // 播放器实例
  final FlutterSoundRecorder _recorder = FlutterSoundRecorder();
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
  bool _isRecording = false; // 是否开始录音
  int _recordingDuration = 0; // 动态记录录音时长 存入数据库的
  double _currentDecibels = 0.0; // 当前分贝
  List<double> _decibelsHistory = []; // 平滑处理队列
  List<Map<String, dynamic>> _recordings = []; // 录音信息列表
  bool _isPlaying = false; // 播放状态
  Duration _currentPosition = Duration.zero; // 当前播放进度
  Duration _totalDuration = Duration.zero; // 音频总时长
  StreamSubscription? _progressSubscription; // 用于管理 onProgress 的监听器
  String _currentPlayingPath = ""; // 当前正在播放的录音路径
  double _playbackSpeed = 1.0; // 播放速度
  int _lastDecibelsUpdate = 0;
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _cancelProgressListener();
    _recorder.closeRecorder();
    super.dispose();
  }

  void updateCurrentPosition(Duration value) {
    setState(() {
      _currentPosition = value;
    });
  }

  void updateTotalDuration(Duration value) {
    setState(() {
      _totalDuration = value;
    });
  }

  void changeIsPlaying( bool ? newValue ) {
    if(newValue != null){
      setState(() {
        _isPlaying = newValue;
      });
    }else{
      setState(() {
        _isPlaying = !_isPlaying;
      });
    }
    
  }

  /// 初始化录音机
  Future<void> initRecorder() async {
    try {
      // 请求录音权限
      bool granted = await PermissionManager.requestPermissions([Permission.microphone]);
      if (!granted) {
        PermissionManager.openSettings(
          context,
          const Text('当前录音权限，建议前往设置开通权限。'),
          Theme.of(context).extension<AppColors>()!,
        );
        return;
      }

      await _recorder.openRecorder();
      // 设置录音进度监听频率
      await _recorder.setSubscriptionDuration(const Duration(milliseconds: 100));
    } catch (e) {
      Logger.error("初始化录音机失败: $e");
    }
  }

  /// 平滑处理分贝值
  double _smoothDecibels(double newValue) {
    if (_decibelsHistory.length >= 100) {
      _decibelsHistory.removeAt(0);
    }
    _decibelsHistory.add(newValue);
    return _decibelsHistory.reduce((a, b) => a + b) / _decibelsHistory.length;
  }

  /// 开始录音
  Future<void> startRecording() async {
    if(_isPlaying){
      _togglePlayPause(_currentPlayingPath);
    }
    await initRecorder();
    Directory appDir = await getApplicationDocumentsDirectory();
    String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    String path = '${appDir.path}/$timestamp.aac';
    setState(() {
      _isRecording = true;
      _recordingDuration = 0; // 初始化录音时长
      _currentDecibels = 0.0;
    });
    await _recorder.startRecorder(
      toFile: path,
      codec: Codec.aacADTS,
    );

    
    // 监听分贝变化和录音时长
    _recorder.onProgress!.listen((event) {
      setState(() {
        _recordingDuration = event.duration.inSeconds;
        // 分贝值监听，限制每 200 毫秒更新一次
        int now = DateTime.now().millisecondsSinceEpoch;
        if (event.decibels != null && now - _lastDecibelsUpdate >= 150) {
          _lastDecibelsUpdate = now;
          _currentDecibels = _smoothDecibels(event.decibels!);
        }
      });
    });
  }

  /// 停止录音
  Future<void> stopRecording() async {
    setState(() {
      _decibelsHistory = [];
    });
    if (_recorder.isStopped) {
      AppPromptOverlay.show(context: context, message: "录音器未打开", position: "top");
      return;
    }
    String? path = await _recorder.stopRecorder();
    setState(() {
      _isRecording = false;
    });
    if (_recordingDuration <= 0) {
      AppPromptOverlay.show(context: context, message: "录制时间最短为1秒", position: "top");
      return;
    }
    if (path != null) {
      await saveRecordingToDatabase(path); // 保存录音信息到数据库
      addRecordingToList(path); // 动态添加到列表
    }
  }

  /// 保存录音信息到数据库
  Future<void> saveRecordingToDatabase(String path) async {
    File file = File(path);
    int size = file.lengthSync(); // 获取文件大小
    await DatabaseHelper.instance.insertRecording({
      'user_id': 'user_1', // 模拟的用户 ID
      'name': '${DateTime.now().millisecondsSinceEpoch}',
      'path': path,
      'duration': _recordingDuration,
      'size': size,
      'create_time': DateTime.now().millisecondsSinceEpoch,
    });

  }

  /// 动态添加录音到列表
  void addRecordingToList(String path) {
    Map<String, dynamic> recording = {
      'name': '${DateTime.now().millisecondsSinceEpoch}',
      'path': path,
      'duration': _recordingDuration,
      'create_time': DateTime.now().millisecondsSinceEpoch,
    };
    _recordings.insert(0, recording); // 插入到列表头部
    _listKey.currentState?.insertItem(0);
  }

  /// 播放或暂停录音
  Future<void> _togglePlayPause(String path) async {
    if (_currentPlayingPath == path) {
      // 如果点击的是当前正在播放的录音
      if (_isPlaying) {
        await _audioPlayer.pausePlayer(); // 暂停播放
        _cancelProgressListener(); // 暂停时移除监听
      } else {
        await _audioPlayer.resumePlayer(); // 恢复播放
        _addProgressListener(); // 恢复播放时添加监听
      }
      changeIsPlaying(null);
    } else {
      try {
        // 如果点击的是新录音
        await _audioPlayer.stopPlayer(); // 停止当前播放
        _cancelProgressListener(); // 停止播放时移除监听
        Duration? result = await _audioPlayer.startPlayer(
          fromURI: path,
          whenFinished: () {
            _cancelProgressListener();
            changeIsPlaying(true);
            updateCurrentPosition(Duration.zero);
            setState(() {
              _currentPlayingPath = "";
            });
            updateCurrentPosition(Duration.zero);
          },
        );
        if (result != null) {
          await _audioPlayer.setSpeed(_playbackSpeed); // 设置倍速
          _addProgressListener(); // 新播放时添加监听
          updateTotalDuration(result);
          updateCurrentPosition(Duration.zero);
          changeIsPlaying(true);
          setState(() {
            _currentPlayingPath = path;
          });
        } else {
          AppPromptOverlay.show(context: context, message: "无法播放录音", position: "top");
        }
      } catch (e, stackTrace) {
        AppPromptOverlay.show(context: context, message: "播放录音出错", position: "top");
        Logger.error("播放录音出错: $path", stackTrace: stackTrace);
      }
    }
  }

  /// 添加监听器
  void _addProgressListener() {
    if (_progressSubscription == null) {
      _progressSubscription = _audioPlayer.onProgress!.listen((event) {
        if (event.duration.inMilliseconds - event.position.inMilliseconds <= 200) {
          updateCurrentPosition(event.duration);
        } else {
          updateCurrentPosition(event.position);
        }
        updateTotalDuration(event.duration);
      });
    }
  }

  /// 移除监听器
  void _cancelProgressListener() {
    _progressSubscription?.cancel();
    _progressSubscription = null;
  }

 

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).extension<AppColors>()!;
    return StatusBarWrapper(
      statusBarColor: theme.subjectPure!,
      statusBarIconBrightness:
          Theme.of(context).brightness == Brightness.dark ? Brightness.light : Brightness.dark,
      child: Scaffold(
        appBar: null,
        body: SafeArea(
          child: Column(
            children: [
              PageNavBar(theme: theme, showTitle: true, title: "面试录音", showRight: false),
              Expanded(
                child: RecordList(
                  theme: theme,
                  listKey: _listKey,
                  addRecordingToList: addRecordingToList,
                  recordings: _recordings,
                  totalDuration: _totalDuration,
                  currentPosition: _currentPosition,
                  isPlaying: _isPlaying,
                  audioPlayer: _audioPlayer,
                  updateCurrentPosition: updateCurrentPosition,
                  updateTotalDuration: updateTotalDuration,
                  togglePlayPause: _togglePlayPause,
                ),
              ),
              // 录音控制按钮
              AnimatedSize(
                duration: const Duration(milliseconds: 120),
                curve: Curves.easeInOut,
                child: Container(
                  width: double.infinity,
                  padding: const EdgeInsets.only(bottom: 16.0, top: 24),
                  decoration: BoxDecoration(
                    color: theme.subjectMix1,
                  ),
                  child: Column(
                    children: [
                      if (_currentPlayingPath.isNotEmpty)
                        RecordPlayer(
                          theme: theme,
                          isPlaying: _isPlaying,
                          currentPosition: _currentPosition,
                          totalDuration: _totalDuration,
                          audioPlayer: _audioPlayer,
                          playPath: _currentPlayingPath,
                          updateCurrentPosition: updateCurrentPosition,
                          togglePlayPause: _togglePlayPause,
                        ),
                      if(_isRecording)
                        RecordInfo(
                          recordingDuration: _recordingDuration,
                          decibelsHistory:_decibelsHistory,
                          theme: theme,
                        ),
                      RecordPlay(
                        theme: theme,
                        isRecording: _isRecording,
                        stopRecording: stopRecording,
                        startRecording: startRecording,
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
